﻿using AutoMapper;
using B.T.BasicData.Domain.RBAC;
using B.T.BasicData.ErrorCode;
using B.T.BasicData.Infraeturcture;
using B.T.BasicData.Write_Api.DTO;
using B.T.BasicData.Write_Api.RBAC.IServices;
using System.Security;
using Yitter.IdGenerator;

namespace B.T.BasicData.Write_Api.RBAC.Services
{
    public class RoleServices : IRoleServices
    {
        private readonly ILogger<RoleServices> logger;
        private readonly IBaseRepository<RolesInfo> roleinfo;
        private readonly IBaseRepository<Role_Permission> role_Permission;
        private readonly IMapper mapper;

        public RoleServices(ILogger<RoleServices> logger,IBaseRepository<RolesInfo> roleinfo,IBaseRepository<Role_Permission> role_Permission,IMapper mapper)
        {
            this.logger = logger;
            this.roleinfo = roleinfo;
            this.role_Permission = role_Permission;
            this.mapper = mapper;
        }

        /// <summary>
        /// 角色添加
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult> AddRole(AddRoleDto dto)
        {
            try
            {
                logger.LogInformation("角色信息添加成功");
                var res = new ApiResult();


                var info = mapper.Map<RolesInfo>(dto);

                info.RolesId=YitIdHelper.NextId();

                //info.Serialnumber = info.Serialnumber + 1;

                info.CreateTime= DateTime.Now;

                

                foreach (var item in dto.PermissionId)
                {
                    var roleperisson = new Role_Permission()
                    {
                        PermissionsId = item,
                        RolesId = info.RolesId,
                    };

                    var tian = await role_Permission.AddAnyx(roleperisson);
                }


                var model=await roleinfo.AddAnyx(info);



                if (model > 0)
                {
                    res.success("角色添加成功");
                    return res;
                }


                return res;



            }
            catch (Exception ex)
            {

                logger.LogError("=>" + ex.Message);
                throw ex;
            }
        }

        /// <summary>
        /// 删除角色信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult> DeleRole(DeleRoleDto dto)
        {
            try
            {
                logger.LogInformation("删除角色信息");

                var res=new ApiResult();

                var rolesinfo = await roleinfo.GetValue(x => x.RolesId.Equals(dto.RolesId));
                if (rolesinfo!=null)
                {
                    rolesinfo.IsDeleted= true;

                    var roelmodel = await roleinfo.Update(rolesinfo);

                    if (roelmodel > 0)
                    {
                        res.success("角色信息删除成功");
                        return res;
                    }


                }

                return res;
            }
            catch (Exception ex)
            {

                logger.LogError("=>" + ex.Message);
                throw ex;
            }
        }

        /// <summary>
        /// 更新角色信息及权限
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> UpdateRole(UpdateRoleDto dto)
        {
            try
            {
                logger.LogInformation($"更新角色信息: {dto.RolesId}");
                var res = new ApiResult();

                // 查询角色
                var rolesinfo = await roleinfo.GetValue(x => x.RolesId.Equals(dto.RolesId) && !x.IsDeleted);
                if (rolesinfo == null)
                {
                    res.msg="未找到该角色";
                    return res;
                }

                // 修改角色基本信息
                rolesinfo.RoleName = dto.RoleName;
                rolesinfo.Serialnumber = dto.Serialnumber;
                var updateResult = await roleinfo.Update(rolesinfo);

                // 先删除原有权限（软删）
                var oldPermissions = role_Permission.Getlist().Where(x => x.RolesId == dto.RolesId && !x.IsDele).ToList();
                foreach (var item in oldPermissions)
                {
                    item.IsDele = true;
                    await role_Permission.Update(item);
                }

                // 添加新权限
                foreach (var pid in dto.PermissionId)
                {
                    var newRel = new Role_Permission
                    {
                        PermissionsId = pid,
                        RolesId = dto.RolesId,
                        IsDele = false
                    };
                    await role_Permission.AddAnyx(newRel);
                }

                res.success("角色信息及权限更新成功");
                return res;
            }
            catch (Exception ex)
            {
                logger.LogError("=>" + ex.Message);
                throw ex;
            }
        }
    }
}
